package com.example.xmpic.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.xmpic.R;
import com.example.xmpic.R2;
import com.example.xmpic.ui.data.CameraLocalFile;
import com.example.xmpic.ui.data.DownloadState;
import com.example.xmpic.ui.utils.LocalFileManager;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author skygge
 * @date 2020/6/23.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：下载管理适配器
 */
public class DownloadAdapter extends RecyclerView.Adapter<DownloadAdapter.ItemHolder> {
    private static final String TAG = DownloadAdapter.class.getSimpleName();
    private Context mContext;
    private List<CameraLocalFile> mDownloadFiles;
    private int mFileSize = 0;
    private int mProgress = 0;

    private onCLickCallBack mCallBack;

    private List<DownloadState> mDownloadState;

    public void setCallBack(onCLickCallBack mCallBack) {
        this.mCallBack = mCallBack;
    }

    public DownloadAdapter(Context mContext) {
        this.mContext = mContext;
        mDownloadState = new ArrayList<>();
    }

    public void setDownloadFiles(List<CameraLocalFile> mDownloadFiles) {
        this.mDownloadFiles = mDownloadFiles;
        initDownloadState();
        notifyDataSetChanged();
    }

    public void setDownState(DownloadState mDownState, int mPosition) {
        mDownloadState.set(mPosition, mDownState);
        notifyItemChanged(mPosition);
    }

    public void setPosition(int totalSize, int progress, int mPosition) {
        mDownloadState.set(mPosition, DownloadState.DOWNLOAD_DOWNING);
        this.mFileSize = totalSize;
        this.mProgress = progress;
        notifyItemChanged(mPosition);
    }

    private void initDownloadState(){
        mDownloadState.clear();
        if (mDownloadFiles!=null && mDownloadFiles.size()>0) {
            for (int i = 0; i < mDownloadFiles.size(); i++) {
                mDownloadState.add(DownloadState.READ_FILE);
            }
        }
    }

    @NonNull
    @Override
    public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_download, viewGroup, false);
        return new ItemHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
        CameraLocalFile mFileData = mDownloadFiles.get(i);
        Glide.with(mContext)
                .load(R.mipmap.camera_thumbnail)
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(12)))
                .into(itemHolder.recordBitmap);
        boolean isLocalFile = mFileData.getIsLocalFile();
        if (isLocalFile){
            mFileSize = mFileData.getFileSize()!=null?Integer.parseInt(mFileData.getFileSize()):0;
            File file = new File(mFileData.getFilepath());
            mDownloadState.set(i, file.exists() ? DownloadState.DOWNLOAD_SUCCESS : DownloadState.READ_FILE);
        }else {
            if (mDownloadState.get(i) == DownloadState.READ_FILE) {
                mDownloadState.set(i, DownloadState.DOWNLOAD_START);
            }
        }
        itemHolder.recordDay.setText(LocalFileManager.getInstance().getBeginDate(mFileData.getDownTime()));
        String name = mFileData.getFilename();
        String time;
        if (name.contains("_")){
            time = name.substring(name.indexOf("_") + 1, name.lastIndexOf("."));
        }else {
            time = name.substring(0, name.lastIndexOf("."));
        }
        itemHolder.recordTime.setText(time);

        String fileSize;
        float mb = (mFileSize/1024f)/1024f;
        if (mb > 1){
            fileSize = new DecimalFormat("##0.0").format(mb) + "M";
        }else {
            float kb = mFileSize/1024f;
            fileSize = new DecimalFormat("##0.0").format(kb) + "K";
        }
        itemHolder.recordSize.setText(fileSize);

        switch (mDownloadState.get(i)){
            case DOWNLOAD_START:
                itemHolder.recordProgress.setProgress(0);
                itemHolder.ivDowning.setImageResource(R.mipmap.icon_downing);
                itemHolder.tvDowning.setText(mContext.getString(R.string.waiting));
                break;
            case DOWNLOAD_SUCCESS:
                itemHolder.recordProgress.setProgress(100);
                itemHolder.ivDowning.setImageResource(R.mipmap.icon_record_stop);
                itemHolder.tvDowning.setText(mContext.getString(R.string.play_it));
                break;
            case DOWNLOAD_DOWNING:
                itemHolder.ivDowning.setImageResource(R.mipmap.icon_downing);
                itemHolder.tvDowning.setText(mContext.getString(R.string.downloading));
                itemHolder.recordProgress.setProgress(mProgress);
                break;
            case READ_FILE:
                itemHolder.ivDowning.setImageResource(R.mipmap.icon_cancel);
                itemHolder.tvDowning.setText(mContext.getString(R.string.file_error));
                itemHolder.recordProgress.setProgress(0);
                break;
        }

        itemHolder.recordPlay.setOnClickListener(v -> {
            if (mDownloadState.get(i) == DownloadState.DOWNLOAD_SUCCESS){
                File file = new File(mFileData.getFilepath());
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri mURI = FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", file);//file即为所要共享的文件的file
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//授予临时权限别忘了
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(mURI, "video/*");
                mContext.startActivity(intent);
            }else if (mDownloadState.get(i) == DownloadState.READ_FILE){
                if (mCallBack!=null) mCallBack.onDeleteLocalFile(mFileData.getDownTime());
            }else {
                if (mCallBack!=null) mCallBack.onDowning();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDownloadFiles == null ? 0 : mDownloadFiles.size();
    }

    static class ItemHolder extends RecyclerView.ViewHolder {
        @BindView(R2.id.record_bitmap)
        ImageView recordBitmap;
        @BindView(R2.id.record_day)
        TextView recordDay;
        @BindView(R2.id.record_progress)
        ProgressBar recordProgress;
        @BindView(R2.id.record_time)
        TextView recordTime;
        @BindView(R2.id.record_size)
        TextView recordSize;
        @BindView(R2.id.tv_record_downing)
        TextView tvDowning;
        @BindView(R2.id.iv_record_downing)
        ImageView ivDowning;
        @BindView(R2.id.record_play)
        LinearLayout recordPlay;
        ItemHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface onCLickCallBack{

        void onDeleteLocalFile(String downTime);

        void onDowning();
    }
}
